package com.industrial.system.service.impl;

import cn.hutool.core.util.IdUtil;
import com.industrial.common.core.constant.UserConstants;
import com.industrial.common.core.exception.ServiceException;
import com.industrial.common.core.utils.SpringUtils;
import com.industrial.common.core.utils.StringUtils;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.system.api.domain.SysUser;
import com.industrial.system.domain.SysUserPost;
import com.industrial.system.domain.SysUserRole;
import com.industrial.system.mapper.SysAdminPersManagMapper;
import com.industrial.system.mapper.SysUserPostMapper;
import com.industrial.system.mapper.SysUserRoleMapper;
import com.industrial.system.service.ISysAdminPersManagService;
import io.swagger.v3.oas.annotations.servers.Server;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysAdminPersManagServiceImpl implements ISysAdminPersManagService {

    @Autowired
    private SysAdminPersManagMapper sysAdminPersManagMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Override
    public List<SysUser> selectUserList(SysUser user) {
        return sysAdminPersManagMapper.selectUserList(user);
    }

    @Override
    public void checkUserDataScope(String userId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId()))
        {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users))
            {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    @Override
    public SysUser selectUserById(String userId) {
        SysUser sysUser = sysAdminPersManagMapper.selectUserById(userId);
        String province = sysUser.getProvince();
        String city = sysUser.getCity();
        String district = sysUser.getDistrict();
        List<String> areaArgs = new ArrayList<String>();
        if(StringUtils.isNotBlank(province) && StringUtils.isNotBlank(city) && StringUtils.isNotBlank(district)){
            areaArgs.add(province);
            areaArgs.add(city);
            areaArgs.add(district);
        }else if(StringUtils.isNotBlank(province) && StringUtils.isNotBlank(city) && StringUtils.isBlank(district)){
            areaArgs.add(province);
            areaArgs.add(city);
        }else if(StringUtils.isNotBlank(province) && StringUtils.isBlank(city) && StringUtils.isBlank(district)){
            areaArgs.add(province);
        }
        sysUser.setAreaCodeArgs(areaArgs);
        return sysUser;
    }

    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin())
        {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    @Override
    public boolean checkUserNameUnique(SysUser user) {
        String userId = StringUtils.isNull(user.getUserId()) ? "-1" : user.getUserId();
        SysUser info = sysAdminPersManagMapper.checkUserNameUnique(user.getUserName());

        if (StringUtils.isNotNull(info) && !StringUtils.equals(info.getUserId(), userId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public boolean checkEmailUnique(SysUser user) {
        String userId = StringUtils.isNull(user.getUserId()) ? "-1" : user.getUserId();
        SysUser info = sysAdminPersManagMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && !StringUtils.equals(info.getUserId(),userId))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(SysUser user) {
        String userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        if(StringUtils.isNotBlank(user.getPassword())){
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        }
        List<String> areaCodeArgs = user.getAreaCodeArgs();
        if(areaCodeArgs != null && !areaCodeArgs.isEmpty()){
            int size = areaCodeArgs.size();
            if(size == 1){
                user.setProvince(areaCodeArgs.get(0));
            }else if(size == 2){
                user.setProvince(areaCodeArgs.get(0));
                user.setCity(areaCodeArgs.get(1));
            }else if (size == 3){
                user.setProvince(areaCodeArgs.get(0));
                user.setCity(areaCodeArgs.get(1));
                user.setDistrict(areaCodeArgs.get(2));
            }
        }
        return sysAdminPersManagMapper.updateUser(user);
    }

    public void insertUserRole(SysUser user)
    {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }

    public void insertUserRole(String userId, String[] roleIds)
    {
        if (StringUtils.isNotEmpty(roleIds))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (String roleId : roleIds)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    public void insertUserPost(SysUser user)
    {
        String[] posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts))
        {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (String postId : posts)
            {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            userPostMapper.batchUserPost(list);
        }
    }

    @Override
    public int insertUser(SysUser user) {
        List<String> areaCodeArgs = user.getAreaCodeArgs();
        if(areaCodeArgs != null && !areaCodeArgs.isEmpty()){
            int size = areaCodeArgs.size();
            if(size == 1){
                user.setProvince(areaCodeArgs.get(0));
            }else if(size == 2){
                user.setProvince(areaCodeArgs.get(0));
                user.setCity(areaCodeArgs.get(1));
            }else if (size == 3){
                user.setProvince(areaCodeArgs.get(0));
                user.setCity(areaCodeArgs.get(1));
                user.setDistrict(areaCodeArgs.get(2));
            }
        }
        user.setUserId(IdUtil.simpleUUID());
        // 新增用户信息
        int rows = sysAdminPersManagMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    @Override
    public int deleteUserById(String userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return sysAdminPersManagMapper.deleteUserById(userId);
    }
}
